/**
 * 
 */
package org.t2.backstage.module.difchannel.quicksdk;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.gaming.ruler.util.HttpUtil;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.tool.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.foundation.starting.ApplicationSettings;
import org.t2.backstage.module.difchannel.quicksdk.QuickSDKUtil.QuickRechargeCBData;
import org.t2.backstage.module.difchannel.quicksdk.QuickSdkProtocol.QuickSdkApiLoginResponse;
import org.t2.backstage.module.difchannel.quicksdk.QuickSdkProtocol.QuickSdkApiRechargeRequest;
import org.t2.backstage.module.difchannel.quicksdk.model.QuickSdkSetting;
import org.t2.backstage.module.difchannel.quicksdk.service.QuickSdkSettingService;
import org.t2.backstage.module.player.model.Player;
import org.t2.backstage.module.player.service.PlayerService;
import org.t2.backstage.module.recharge.model.RechargeCallback;
import org.t2.backstage.module.recharge.service.RechargeCallbackService;
import org.t2.backstage.module.recharge.service.RechargeStatus;

import sh.t2.share.apiutil.ApiUtil;
import sh.t2.share.module.recharge.RechargeExtra;

/**
 * 
 */
@Controller
public class QuickSdkApiController {

	private static Logger logger = LoggerFactory.getLogger(QuickSdkApiController.class);

	@Autowired
	private QuickSdkSettingService quickSdkSettingService;
	@Autowired
	private RechargeCallbackService rechargeCallbackService;
	@Autowired
	private ApplicationSettings applicationSettings;
	@Autowired
	private PlayerService playerService;
	
	/**
	 * /api/quicksdk/login?token=1&uid=2&channelCode=3
	 * @param token
	 * @param uid
	 * @param channelCode
	 * @return
	 */
	@ApiDocument("登录验证，给游戏客户端请求用的")
	@RequestMapping(value = "/api/quicksdk/login")
	@ResponseBody
	public QuickSdkApiLoginResponse login(@RequestParam("token") String token, @RequestParam("uid") String uid,
			@RequestParam("channelCode") String channelCode) {
		QuickSdkSetting setting = quickSdkSettingService.getSetting();

		logger.info("QuickSdk验证登录token：{}", token);
		logger.info("QuickSdk验证登录uid：{}", uid);
		logger.info("QuickSdk验证登录channelCode：{}", channelCode);

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("uid", uid);
		map.put("channel_code", channelCode);
		String quickResponse = HttpUtil.formPost(setting.getLoginUrl(), map);

		logger.info("QuickSdk登录验证响应：{}", quickResponse);

		QuickSdkApiLoginResponse response = new QuickSdkApiLoginResponse();
		if (quickResponse.equals("1")) {
			response.uid = uid;
		} else {
			response.uid = "";
		}
		return response;
	}

	@ApiDocument("充值回调")
	@RequestMapping(value = "/api/quicksdk/recharge")
	@ResponseBody
	public String recharge(@RequestParam("nt_data") String nt_data, @RequestParam("sign") String sign,
			@RequestParam("md5Sign") String md5Sign) {
		QuickSdkApiRechargeRequest request = new QuickSdkApiRechargeRequest();
		request.nt_data = nt_data;
		request.sign = sign;
		request.md5Sign = md5Sign;
		
		QuickSdkSetting setting = quickSdkSettingService.getSetting();

		logger.info("收到充值回调: {}", GsonUtil.toJson(request));

		String waitSign = request.nt_data + request.sign + setting.getMd5Key();
		String localSign = ApiUtil.buildSign(waitSign);
		logger.info("Quick充值回调签名原文：{}", waitSign);
		logger.info("Quick充值回调签名：{}", request.md5Sign);
		logger.info("Quick充值回调本地签名：{}", localSign);

		RechargeCallback recharge = new RechargeCallback();
		try {
			recharge.setCallbackData(GsonUtil.toJson(request));
			
			String xmlData = QuickSDKUtil.decode(request.nt_data, setting.getCallbackkey());
			QuickRechargeCBData cdData = QuickSDKUtil.fromDom(xmlData);
			logger.info("Quick回调解码数据：{}", GsonUtil.toJson(cdData));

			BigDecimal bigPayMoney = new BigDecimal(cdData.getAmount()).multiply(new BigDecimal("100"));
			// 单位分
			long payMoney = bigPayMoney.longValue();

			String sdkOrderId = cdData.getOrder_no();
			String gameOrderId = cdData.getGame_order();

			String decodeExt = cdData.getExtras_params();
			try {
				decodeExt = URLDecoder.decode(decodeExt, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			// 验签扩展参数
			RechargeExtra rechargeExtra = RechargeExtra.decode(decodeExt);
			String localExtraSign = rechargeExtra.buildSign(applicationSettings.getBackstageKey());

			// 验签数据
			recharge.setSign(md5Sign);
			recharge.setLocalSign(localSign);
			recharge.setExtraSign(rechargeExtra.getSign());
			recharge.setLocalExtraSign(localExtraSign);
			recharge.setAllCheck(true);

			if (localSign.equals(md5Sign)) {
				recharge.setRemark("验签通过");
			} else {
				recharge.setRemark("验签不通过");
				recharge.setAllCheck(false);
			}
			if (localExtraSign.equals(rechargeExtra.getSign())) {
				recharge.setRemark("扩展验签通过");
			} else {
				recharge.setRemark("扩展验签不通过");
				recharge.setAllCheck(false);
			}
			// 配置里面填的单位是元
			if (payMoney == rechargeExtra.getMoney() * 100) {
				recharge.setRemark("金额一致");
			} else {
				recharge.setRemark("金额不一致");
				recharge.setAllCheck(false);
			}

			// 获取请求IP
			recharge.setSdkOrderId(sdkOrderId);
			recharge.setGameOrderId(gameOrderId);

			Player player = playerService.getEntity(rechargeExtra.getPlayerId());
			recharge.setPlayerId(rechargeExtra.getPlayerId());
			if (player != null) {
				recharge.setNick(player.getNick());
				recharge.setPlatformId(player.getPlatformId());
				recharge.setChannelId(player.getChannelId());
				recharge.setServerId(player.getServerId());
			}
			recharge.setOpenId(rechargeExtra.getOpenId());

			recharge.setMoney(payMoney);
			recharge.setProductId(rechargeExtra.getProductId());
		} catch (Exception e) {
			logger.error("", e);
			return "FAILED";
		} finally {
			rechargeCallbackService.insert(recharge);
		}
		RechargeStatus rechargeStatus = rechargeCallbackService.handleCallback(recharge);
		if (rechargeStatus == RechargeStatus.SUCCESS || rechargeStatus == RechargeStatus.REPEATED) {
			return "SUCCESS";
		} else {
			return "FAILED";
		}
	}
}
